import { ElButton, ElDialog, ElInput } from "element-plus";
import { createVNode, defineComponent, reactive, render } from "vue";

const dialogComponent = defineComponent({
  props: {
    option: { type: Object },
  },
  setup(props, ctx) {
    const state = reactive({
      option: props.option,
      isShow: false,
    });
    // 让外界通过虚拟节点显示和隐藏组件
    ctx.expose({
      showDialog(option) {
        state.option = option;
        state.isShow = true;
      },
    });
    // 关闭对话框
    const cancel = () => {
      state.isShow = false;
    };
    // 确认
    const confirm = () => {
      state.isShow = false;
      state.option.onConfirm && state.option.onConfirm(state.option.content);
    };
    return () => {
      return (
        <ElDialog v-model={state.isShow} title={state.option.title}>
          {{
            default: () => {
              return (
                <ElInput
                  type="textarea"
                  v-model={state.option.content}
                  rows={10}
                ></ElInput>
              );
            },
            footer: () =>
              state.option.footer && (
                <div>
                  <ElButton onClick={cancel}>取消</ElButton>
                  <ElButton type="primary" onClick={confirm}>
                    确定
                  </ElButton>
                </div>
              ),
          }}
        </ElDialog>
      );
    };
  },
});
let vm;
export function $dialog(option) {
  // 手动挂载组件
  // 如果组件已经存在只需要显示就行了
  if (!vm) {
    let el = document.createElement("div");
    // 创建虚拟节点
    vm = createVNode(dialogComponent, { option });
    // 渲染虚拟节点:
    // 1.将组件渲染到el元素上
    render(vm, el);
    // 2.将el元素渲染到页面上
    document.body.appendChild(el);
  }

  // 显示弹窗组件
  let { showDialog } = vm.component.exposed;
  showDialog(option);
}
